package org.example.wx.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.common.utils.ResponseUtil;
import org.example.db.entity.CategoryFirst;
import org.example.db.entity.CategorySecond;
import org.example.db.mapper.CategoryFirstMapper;
import org.example.db.mapper.CategorySecondMapper;
import org.example.wx.exception.DataNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class WxCategoryService {

    CategoryFirstMapper categoryFirstMapper;
    CategorySecondMapper categorySecondMapper;

    public WxCategoryService(CategoryFirstMapper categoryFirstMapper, CategorySecondMapper categorySecondMapper) {
        this.categoryFirstMapper = categoryFirstMapper;
        this.categorySecondMapper = categorySecondMapper;
    }
    public List<CategoryFirst> getFirstCategoryList(){

        return categoryFirstMapper.selectList(
                new QueryWrapper<CategoryFirst>().lambda().orderByAsc(CategoryFirst::getSortOrder));

    }

    /**
     *
     * @param id category id , if id is null, the method will get the first record of database which order by sort_order
     * @return CategoryFirst
     */
    public CategoryFirst getFirstCategory(Long id){

        CategoryFirst categoryFirst = null;

        if(id == null){
            categoryFirst = categoryFirstMapper.selectOne(
                    new QueryWrapper<CategoryFirst>().lambda().orderByAsc(CategoryFirst::getSortOrder).last("limit 1"));
        }else {
            categoryFirst = categoryFirstMapper.selectById(id);
        }


        return categoryFirst;
    }

    public List<CategorySecond> getCategorySecondListParentId(Long parentId){

        return categorySecondMapper.selectList(new QueryWrapper<CategorySecond>().lambda()
                .eq(CategorySecond::getParentId, parentId).orderByAsc(CategorySecond::getSortOrder));
    }

    public CategoryFirst getParentCategoryBySecondaryId(Long categoryId){

        List<CategorySecond> categorySecondList = categorySecondMapper.selectList(
                new QueryWrapper<CategorySecond>().lambda()
                        .eq(CategorySecond::getId, categoryId).orderByDesc(CategorySecond::getSortOrder));

        if(categorySecondList.isEmpty()){
            throw new DataNotFoundException("secondary category not found (by id)");
        }
        CategorySecond categorySecond = categorySecondList.get(0);
        return categoryFirstMapper.selectById(categorySecond.getParentId());
    }

    public CategorySecond getCategorySecond(Long id){

        return categorySecondMapper.selectById(id);
    }


}
